/*
 *  AMGlobal.h
 *  AMPlugin
 *
 *  Created by Tiet Anh Vu on 5/30/12.
 *  Copyright 2012 __MyCompanyName__. All rights reserved.
 *
 */

#include "VCPlugInHeaders.h"

// Interface includes:
#include "IDialogMgr.h"
#include "IDialog.h"
#include "IApplication.h"
#include "ILinkObject.h"

// General includes:
#include "UIDList.h"
#include "CoreResTypes.h"
#include "LocaleSetting.h"
#include "RsrcSpec.h"


// Framework includes:
#include "AMPID.h"
#include "SnpRunnable.h"
#include "AMGlobal.h"
#include "AMPDocument.h"
#include "StringUtils.h"
#include "IIDMLComponentName.h"
#include "AMPCAlert.h"
#include "IFrmLblData.h"
//#include <iostream>
//using namespace std;


class SnpHandleGraphicFrame
{

	public:
	
		/** Constructor.
		*/
		SnpHandleGraphicFrame() {}

		/** Destructor
		*/
		virtual ~SnpHandleGraphicFrame() {}

};

// --------------------------------- SnippetRunner framework hooks ---------------------------------------------------

/** Makes the snippet SnpHandleGraphicFrame available to the SnippetRunner framework.

  	@ingroup sdk_snippet_run
	
 */
class _SnpHandleGraphicFrame : public SnpRunnable
{
	public:
		// For SnippetRunner framework.

		/** Constructor.
		*/
		_SnpHandleGraphicFrame();

		/** Destructor
		*/
		virtual ~_SnpHandleGraphicFrame();

		/** Return kTrue if the snippet can run.
			@param runnableContext see ISnpRunnableContext for documentation.
			@return kTrue if a document is open, kFalse otherwise
		 */
		bool16			CanRun(ISnpRunnableContext* runnableContext);

		/** Run the snippet.
			@param runnableContext see ISnpRunnableContext for documentation.
			@return kSuccess on success, other ErrorCode otherwise.
		*/
		ErrorCode		Run(ISnpRunnableContext* runnableContext);	

		/** Don't present this snippet in the framework's UI if the
			product we are running under is InCopy. 
			@return kFalse if the host product is InCopy, kTrue otherwise.
		*/
		bool16 CanLoad() const;
		
		/** 
			get the snippet context
			@return eSnpRunContextType for this snippet
		*/
		virtual ISnipRunSuite::eSnpRunContextType GetContext(void){return ISnipRunSuite::kSnpRunLayoutTargetContext;}
};

/* Constructor
*/
_SnpHandleGraphicFrame::_SnpHandleGraphicFrame() : SnpRunnable("HandleGraphicFrame")
{
	this->SetDescription("Applies and inspects graphic attributes of various types (stroke weight, stroke colour, fill colour etc.)");
	this->SetPreconditions("page item selected");
	this->SetCategories("sdk_snippet, sdk_graphic");
}

/* Destructor
*/
_SnpHandleGraphicFrame::~_SnpHandleGraphicFrame()
{
}

/*
*/
bool16 _SnpHandleGraphicFrame::CanRun(ISnpRunnableContext* runnableContext)
{
	bool16 result = kFalse;
	HandleSelectedStatusFrame = kNoStatus;
	// Require a layout selection to be able to run.
	InterfacePtr<ILayoutTarget> layoutTarget(runnableContext, UseDefaultIID());
	if (layoutTarget != nil) {
		UIDList itemList = layoutTarget->GetUIDList(kStripStandoffs);
		if (itemList.Length() > 0) {
			result = kTrue;
		}
		
		do {
			UIDRef fatherUIDRef = itemList.GetRef(0);
			if(fatherUIDRef == UIDRef::gNull)
				break;
			
			FrmLblInfo frmLblInfo;
			Utils<IFrmLblDataFacade>()->GetFrameLabelProperties(fatherUIDRef, frmLblInfo);
			HandleSelectedStatusFrame = frmLblInfo.status;
			
		}while(kFalse);
		//printf("\nupdating the attributes of the label:%d\n",frmLblInfo.status);
		
		// updating the attributes of the label
	}
	
	return result;
}

/* 
*/
ErrorCode _SnpHandleGraphicFrame::Run(ISnpRunnableContext* runnableContext)
{
	ErrorCode status = kSuccess;
	
	
	if (g_IsLoggedIn == FALSE) {
		AMPCAlert::ModalAlert (
							PMString("\n\nPlease login and check-out first."),		// Alert string
							kOKString,						// OK button
							kNullString,					// No second button
							kNullString, 					// No third button
							kNoNeedToWaitForDialog,		// Set OK button to default
							1								// No icon.
							);
		return kFailure;
	}
	
	if (g_DocName.compare(AMPUtils::FrontDocName()) != 0) {
		AMPCAlert::ModalAlert (
							PMString("\n\nFunction not available."),		// Alert string
							kOKString,						// OK button
							kNullString,					// No second button
							kNullString, 					// No third button
							0,								// Set OK button to default
							1								// No icon.
							);
		return kFailure;
	}
	

	bool shouldDisplayDlg = FALSE;
	do 
	{
		// Require a layout selection to be able to run.
		InterfacePtr<ILayoutTarget> layoutTarget(runnableContext, UseDefaultIID());
		if (layoutTarget == nil) 
		{
			break;
		}
		UIDList itemList = layoutTarget->GetUIDList(kStripStandoffs);
		if (itemList.Length() <= 0 ) 
		{
			break;
		}
		//cout << "number of item: " << itemList.Length() << endl;
		
		InterfacePtr<IHierarchy> frameHierarchy(itemList.GetRef(0), UseDefaultIID());
		InterfacePtr<IHierarchy> childHierarchy(frameHierarchy->QueryChild(0));
		// If we're on a placed image we should have a data link to source item 
		InterfacePtr<ILinkObject> iLinkObject(childHierarchy,UseDefaultIID()); // get the link for this object
		IDataBase* iDataBase = ::GetDataBase(childHierarchy); 
		
		if (!iDataBase) {
			cout << "iDataBase is nil" << endl;
			break;
		}
		
		InterfacePtr<ILinkManager> iLinkManager(iDataBase,iDataBase->GetRootUID(),UseDefaultIID()); 
		ILinkManager::QueryResult linkQueryResult;
		if (iLinkManager->QueryLinksByObjectUID(::GetUID(childHierarchy), linkQueryResult)) {
			ASSERT_MSG(linkQueryResult.size()==1, "Only expecting single link with this object");
			ILinkManager::QueryResult::const_iterator iter = linkQueryResult.begin(); InterfacePtr<ILink> iLink (iDataBase, *iter,UseDefaultIID()); 
			if (iLink!=nil) {
				InterfacePtr<ILinkResource> iLinkResource(iLinkManager->QueryResourceByUID(iLink->GetResource()));
				ASSERT_MSG(iLinkResource,"CHMLFiltHelper::addGraphicFrameDescription - Link with no associated asset?");
				if(iLinkResource!=nil) {
					PMString datalinkPath = iLinkResource->GetLongName(FALSE);
					PMString datalinkName = iLinkResource->GetShortName(FALSE);
					cout<< "datalinkPath: " << datalinkPath.GrabCString() << endl;
					g_ChosenImagePath = datalinkPath.GrabCString();
					//g_ChosenImageName = datalinkName.GrabCString();
					
					string temp = datalinkPath.GrabCString();
					temp = temp.substr(0, temp.find_last_of("//"));
					temp = temp.substr(temp.find_last_of("//")+1);
					g_ChosenImageName = temp + "_" + datalinkName.GrabCString();
					//cout << "g_ChosenImageName: " << g_ChosenImageName << endl;
					shouldDisplayDlg = TRUE;
				}
			}
		}
		
	} while(false);
	
	if (shouldDisplayDlg == TRUE) {
		do {
			
			string linksDirPath = g_System_WorkspaceDir + "/" + "Links/";
			cout << "g_ChosenImagePath: " << g_ChosenImagePath << endl;
			//cout << "linksDirPath: " << linksDirPath << endl;
			if (g_ChosenImagePath.find(linksDirPath) != string::npos) {
				AMPCAlert::ModalAlert (
									PMString("\n\nImage already assigned. Please assign a new image."),		// Alert string
									kOKString,						// OK button
									kNullString,					// No second button
									kNullString, 					// No third button
									kNoNeedToWaitForDialog,			// Set OK button to default
									1								// No icon.
									);
				break;
			}
			
			int32	DialogResourceID;
			
			DialogResourceID = kImgAssignmentDlgRsrcID;
			// Get the application interface and the DialogMgr.	
			InterfacePtr<IApplication> application(GetExecutionContextSession()->QueryApplication());
			if (application == nil)
			{
				ASSERT_FAIL("BscDlgActionComponent::DoDialog: application invalid");
				break;
			}
			InterfacePtr<IDialogMgr> dialogMgr(application, UseDefaultIID());
			if (dialogMgr == nil)
			{ 
				ASSERT_FAIL("BscDlgActionComponent::DoDialog: dialogMgr invalid"); 
				break;
			}
			// Load the plug-in's resource.
			PMLocaleId nLocale = LocaleSetting::GetLocale();
			RsrcSpec dialogSpec
			(
				nLocale,					// Locale index from PMLocaleIDs.h. 
				kAMPPluginID,				// Our Plug-in ID from BasicDialogID.h. 
				kViewRsrcType,				// This is the kViewRsrcType.
				DialogResourceID,			// Resource ID for our dialog.
				kTrue						// Initially visible.
			 );
			
			// CreateNewDialog takes the dialogSpec created above, and also
			// the type of dialog being created (kMovableModal).
			IDialog* dialog = dialogMgr->CreateNewDialog(dialogSpec, IDialog::kMovableModal);
			
			if (dialog == nil)
			{ 
				ASSERT_FAIL("BscDlgActionComponent::DoDialog: can't create dialog"); 
				break;
			}
			
			// reset variables
			g_ChosenStoryID = "";
			
			// Open the dialog.
			dialog->Open();

		} while (kFalse);
		
	} 
	else {
		//cout << "oops, text frame selected" << endl;
		AMPCAlert::ModalAlert
		(
			PMString("Text frame selected.\n\nPlease select graphic frame to assign graphic."),		// Alert string
			kOKString,						// OK button
			kNullString,					// No second button
			kNullString, 					// No third button
			kNoNeedToWaitForDialog,			// Set OK button to default
			1								// No icon.
		 );
	}	// end shouldDisplayDlg == TRUE
	
	
	return status;
}

/* 
*/
bool16  _SnpHandleGraphicFrame::CanLoad() const
{
	bool16 result = kTrue;
	if (LocaleSetting::GetLocale().IsProductFS(kInCopyProductFS)) {
		// Graphic attributes can be applied to page items under InCopy
		// but we don't load this snippet because there's no pointer tool 
		// to select a page item with. If we loaded the snippet the Go 
		// button for the snippet would mostly be disabled.
		result = kFalse;
	}
	return result;
}

/*	Declare an instance to register the snippet hook with the framework.
*/
static _SnpHandleGraphicFrame instance_SnpHandleGraphicFrame;
DEFINE_SNIPPET(_SnpHandleGraphicFrame) 	
//End, SnpHandleGraphicFrame.cpp
